package com.chart.web.controller.common.ai;

import com.aliyun.imagerecog20190930.models.RecognizeImageColorResponse;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.chart.common.core.domain.AjaxResult;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import static com.chart.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 *
 视觉智能开放平台

 */
@RestController
@RequestMapping("")
public class RecognizeImageColorController {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 创建阿里云客户端实例
     */
    private com.aliyun.imagerecog20190930.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "imagerecog.cn-shanghai.aliyuncs.com";  // 图像识别服务的 endpoint
        return new com.aliyun.imagerecog20190930.Client(config);
    }


    @PostMapping("/analyze")
    public AjaxResult analyzeImageColor(@RequestParam("file") MultipartFile file) throws IOException {
        if (ObjectUtils.isEmpty(file)) {
            log.warn("上传文件为空");
            return AjaxResult.warn("上传文件为空");
        }

        // 校验文件大小不超过9.5MB
        long maxFileSize = 5 * 1024 * 1024 + 512 * 1024; // 9.5MB
        if (file.getSize() > maxFileSize) {
            log.warn("文件大小超过限制，文件大小: {} bytes", file.getSize());
            return new AjaxResult(602, "您上传的图片超过5M，请重新上传！");
        }

        // 校验文件格式（PNG、JPG、JPEG、BMP）
        List<String> allowedFormats = Arrays.asList("PNG", "JPG", "JPEG", "BMP");
        String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename()).toUpperCase();
        if (!allowedFormats.contains(fileExtension)) {
            log.warn("文件格式不支持: {}", fileExtension);
            return new AjaxResult(601, "仅支持 PNG、JPG、JPEG、BMP 格式的图片");
        }


        // 检查并调整图像尺寸
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();

        // 如果图片宽度或高度大于2500，则进行调整
        if (width > 2500 || height > 2500) {
            bufferedImage = Thumbnails.of(bufferedImage)
                    .size(2500, 2500) // 设置最大宽高为 2500
                    .asBufferedImage();
            log.info("图片分辨率超出限制，已调整尺寸至 2500 像素以内");
        }

        // 将调整后的图片写入 ByteArrayOutputStream 中
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStream);  // 假设图像格式为 JPG
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

        // 创建 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String uniqueFileName = "uploads/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();

        try {
            // 上传调整后的文件到 OSS
            ossClient.putObject(bucketName, uniqueFileName, inputStream);

            // 设置文件为公共读
            ossClient.setObjectAcl(bucketName, uniqueFileName, CannedAccessControlList.PublicRead);

            // 构造图片 URL
            String imageUrl = "https://" + bucketName + "." + endpoint + "/" + uniqueFileName;
            log.info("上传文件 URL: {}", imageUrl);

            // 使用阿里云客户端创建请求
            com.aliyun.imagerecog20190930.Client client = createClient(accessKeyId, accessKeySecret);
            com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest request = new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                    .setUrl(imageUrl)
                    .setColorCount(6);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            // 发送请求并接收响应
            RecognizeImageColorResponse response = client.recognizeImageColorWithOptions(request, runtime);
            String jsonResponse = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response));

            // 解析返回结果
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonResponse);
            List<String> colors = new ArrayList<>();
            JsonNode colorTemplateList = jsonNode.path("body").path("Data").path("ColorTemplateList");
            System.out.println(colorTemplateList);

            // 遍历数组并提取 "Color" 字段的值，并在前面添加 "#"
            for (JsonNode colorNode : colorTemplateList) {
                String color = "#" + colorNode.path("Color").asText();  // 添加 "#" 前缀
                colors.add(color);
            }

            // 返回结果
            HashMap<Object, Object> map = new HashMap<>();
            map.put("colors", colors);
            log.info("识别的颜色: {}", colors);
            return AjaxResult.success(map);

        } catch (TeaException e) {
            log.error("阿里云 API 调用失败: {}", e.getMessage(), e);
            return AjaxResult.error("阿里云 API 调用失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传或处理失败: {}", e.getMessage(), e);
            return AjaxResult.error("上传或处理文件失败: " + e.getMessage());
        } finally {
            // 确保关闭 OSS 客户端
            if (ossClient != null) {
                try {
                    // 删除 OSS 中的文件
                    ossClient.deleteObject(bucketName, uniqueFileName);
                    log.info("已删除 OSS 中的文件: {}", uniqueFileName);
                } catch (Exception deleteException) {
                    log.warn("删除 OSS 文件失败: {}", deleteException.getMessage());
                }
                ossClient.shutdown();
            }
            // 关闭流
            outputStream.close();
            inputStream.close();
    }


}}
